<template>
  <div class="app-container">
    <el-button type="success" icon="el-icon-document-add" style="margin-left: 10px" @click="drawerAddUser = true">
      添加商品
    </el-button>
    <template>
      <el-table :data="tableData" style="width: 100%">


        <el-table-column label="商品编号" prop="id"></el-table-column>
        <el-table-column label="商品名称" prop="name"></el-table-column>

        <el-table-column label="商品单价" prop="price"></el-table-column>
        <el-table-column label="商品状态" prop="state" :formatter="stateFormat"></el-table-column>
        <el-table-column show-overflow-tooltip class-name="cell-text-ellipsis" label="商品描述" prop="description">
        </el-table-column>
        <el-table-column label="商品图片">
          <template slot-scope="props">
            <img :src="props.row.imageUrl" alt="" width="50" height="50">
          </template>
        </el-table-column>




        <el-table-column align="right">
          <template slot="header" slot-scope="scope">
            <el-input @input="change" v-model="search" size="mini" placeholder="输入关键字搜索" />
          </template>
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="handleEdit(scope.$index, scope.row)">删除</el-button>
            <el-button v-if="scope.row.productStatus!='已完成'" size="mini" @click="xiugai(scope.$index)">
              {{scope.row.state=='0'?'下架':'上架'}}

            </el-button>
            <el-button size="mini" @click="drawerAddUser = true;update(scope.row.id)">编辑</el-button>
            <!-- <el-button size="mini" @click="drawerAddUser = true;update(scope.row.userId);">编辑</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </template>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" @prev-click="prevClick"
        @next-click="nextClick" :current-page="currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="5"
        layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <div class="app-container">
      <el-drawer title="编辑基本信息" :visible.sync="drawerAddUser" :direction="direction" :before-close="handleClose"
        size="40%">

        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini" class="demo-ruleForm">
          <div class="modal-body">
            <el-form-item label="商品名称">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="商品单价">
              <el-input v-model="ruleForm.price"></el-input>
            </el-form-item>
            <el-form-item label="商品状态" prop="phoneNumber">
              <template>
                <div>
                  <select v-model="ruleForm.state">
                    <option disabled value="">请选择一个选项</option>
                    <option v-for="option in options" :key="option.value" :value="option.value">
                      {{ option.text }}
                    </option>
                  </select>
                  <p>选中的值: {{ ruleForm.state }}</p>
                </div>
              </template>
            </el-form-item>
            <el-form-item label="商品描述" prop="description">
              <el-input v-model="ruleForm.description"></el-input>
            </el-form-item>

            <el-form-item label="照片">
              <template>
                <div>

                  <img :src="ruleForm.imageUrl" width="50" height="50" alt="">
                  <input type="file" @change="handleFileUpload">

                </div>
              </template>

            </el-form-item>

          </div>
          <el-form-item>
            <el-button @click="cancelForm; ">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm',ruleForm.id)">确认</el-button>
          </el-form-item>
        </el-form>

      </el-drawer>
    </div>
  </div>
</template>

<script>
  import {
    userList,

    deleteUser,


  } from '@/api/user';
  import {
    orderList,

    deleteOrder
  } from '@/api/order';
  import {
    productList,
    update2,
    deleteProduct,
    add,
    updateUserFlagById,
    update3

  } from '@/api/product';
  import axios from 'axios';



  export default {
    data() {
      return {
        selectedOption: '',
        options: [{
            text: '已上架',
            value: '0'
          },
          {
            text: '已下架',
            value: '1'
          }
        ],
        file: null, // 用于存储选中的文件
        value: '切换',
        btnname: '',
        flag: 'Y',
        tableData: [],
        currentPage: 1,
        pageNum: 1,
        pageSize: 5,
        total: '',
        search: '',
        formInline: {
          lxmc: '',
          lxpri: 0,
          xybz: ''
        },
        ruleForm: {
          imageUrl: ''

        },
        rules: {
          lxmc: [{
              required: true,
              message: '请输入类型名称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 5,
              message: '长度在2 到 5 个字符',
              trigger: 'blur'
            }
          ],
          xybz: [{
            required: true,
            message: '请选择是否启用',
            trigger: 'change'
          }],
          lxbz: [{
            required: true,
            message: '请填写类型备注',
            trigger: 'blur'
          }]
        },
        drawerAddUser: false,
        direction: 'rtl',
        loading: false
      };
    },
    computed: {
      generateStars() {
        return (length) => {
          return '*'.repeat(length);
        };
      },

    },
    methods: {
      handleFileUpload(event) {
        this.file = event.target.files[0];
        const postData = new FormData();

        postData.append('multipartFile', this.file)
        axios.post('http://150.158.51.212:8080/my/upload', postData).then(
            res => {

              console.log(res.data)
              this.ruleForm.imageUrl = res.data.data
            }
          ).catch(error => {
            console.error('Error posting data:', error);
          })
          .finally(() => {
            console.log('POST request finished.');
          });
      },
      submitFile() {
        console.log(this.file)
        if (!this.file) {
          alert('请先选择一个文件！');
          return;
        }



      },
      change() {


        this.getList();

      },

      update(id) {
        this.loading = true;
        updateUserFlagById(id).then(res => {
          console.info('res==>', res);
          this.ruleForm = res
          this.loading = true;
        })
      },
      getList() {
        this.loading = true;
        productList(this.pageNum, this.pageSize, this.search).then(res => {
          console.info('resdsfsad==>', res);
          this.tableData = res.list;
          this.total = res.total;
          this.loading = false;

        });
      },
      stateFormat(row, column, cellValue) {

        return row[column.property] == '1' ? '已下架' : '已上架';
      },
      dateFormat(row, column) {
        return row[column.property].replace('T', ' ');
      },
      togglePasswordVisibility(index) {

        this.tableData[index].showRealPasswords = !this.tableData[index].showRealPasswords

      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pageNum = val;
        this.getList();
      },
      prevClick(val) {
        this.pageNum = val;
        this.getList();
      },
      nextClick(val) {
        this.pageNum = val;
        this.getList();
      },
      getListByFlag() {
        this.loading = true;
        userList(this.flag).then(res => {
          this.listLoading = false;
        });
      },
      handleEdit(index, row) {
        console.log(index, row);
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProduct(row.id).then(res => {
            this.loading = true;
            if (res) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
              this.getList();
            } else {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            }
          }).catch(() => {
            this.loading = false;
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        });
      },

      handleDisable(index, row) {
        console.log(index, row.id);
        if (row.id == 1) {
          this.$message({
            type: 'success',
            message: '当前用户不可禁用'
          });
          return;
        }
        this.$confirm('此操作将更改用户名称为' + row.username + '的应用状态, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          // 执行禁用方法
          updateUserFlagById({
            id: row.id,
            flag: row.flag
          }).then(res => {
            this.listLoading = false;
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: res.message
              });
              this.getList();
            } else {
              this.$message({
                type: 'error',
                message: res.message
              });
            }
          });
        }).catch(() => {
          this.loading = false;
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      handleClose(done) {

        this.$confirm('确定要提交表单吗？').then(_ => {
          this.loading = true;

          done();
          this.ruleForm = [];

          // 动画关闭需要一定的时间

          this.loading = false;

        }).catch(_ => {});
      },
      cancelForm() {
        this.loading = false;
        this.drawerAddUser = false;
        clearTimeout(this.timer);
      },
      submitForm(formName, id) {


        this.$refs[formName].validate((valid) => {
          console.log(this.ruleForm.value)

          if (valid) {
            this.loading = true;
            if (id != '' && id != null) {
              this.update3()
            } else {
              this.tianjia();
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      update3() {
        update3(this.ruleForm).then(res => {
          this.loading = false;
          if (true) {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.ruleForm = []
            this.drawerAddUser = false;
            this.getList();
          } else {
            this.$message({
              type: 'error',
              message: res.message
            });
          }
        }).catch(() => {
          this.loading = false;
          this.$message({
            type: 'error',
            message: '修改失败!'
          });
        });


      },
      xiugai(index) {
        console.log("撒大苏打", this.tableData[index])
        update2(this.tableData[index]).then(res => {
          this.getList();


        }).catch(() => {
          this.$message({
            type: 'error',
            message: '修改失败!'
          });
        })

      },
      tianjia() {
        add(this.ruleForm).then(res => {
          this.loading = false;
          if (true) {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.drawerAddUser = false;
            this.getList();
          } else {
            this.$message({
              type: 'error',
              message: res.message
            });
          }
        }).catch(() => {
          this.loading = false;
          this.$message({
            type: 'error',
            message: '添加失败!'
          });
        });
      },
    },

    mounted() {
      this.getList();
    }
  };
</script>

<style scoped>
  .el-pagination {
    float: right;
    margin: 10px;
  }

  .modal-body {
    overflow-y: auto;
    /* 垂直滚动条 */
    max-height: 500px;
    /* 限制最大高度 */
  }

  .cell-text-ellipsis {
    height: 40px;
    /* 设置一个固定高度 */
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
